<?php
namespace Fendx\Doctrine;

use Doctrine\ORM\QueryBuilder;

class Utils {

    public static function generalWhereByCriteria($criteria) {
        if (empty($criteria)) {
            return [];
        }
        $where = [];
        foreach ($criteria as $key => $value) {
            if (is_array($value)) {
                $where[] = [$key, 'in', $value];
            } else {
                $where[] = [$key, $value];
            }
        }
        return $where;
    }

    /**
     * 根据where生成QueryBuilder
     *
     * @var $where array|string  [['name', 'lichao'], ['id', '>', 5]]
     */
    public static function generalQueryBuilderByWhere(QueryBuilder $qb, string $alias, array $where = []) {
        if (empty($where)) {
            return;
        }
        if (!is_array($where)) {
            return;
        }
        $filedMaps = [];
        foreach ($where as $_where) {
            if (!is_array($_where)
                || (count($_where) != 2 && count($_where) != 3)
            ) {
                throw new \Exception('where format error');
            }

            $field = $_where[0];
            $filedMaps[$field] = isset($filedMaps[$field]) ? $filedMaps[$field] + 1 : 0;
            $filedAlias = sprintf("%s__%s", $field, $filedMaps[$field]);
            $fieldAndAlias = sprintf('%s.%s', $alias, $field);

            // `name` => 'val'
            if (count($_where) == 2) {
                $format = sprintf('%s = :%s', $fieldAndAlias, $filedAlias);
                $value = $_where[1];

            } else if (count($_where) == 3) {
                // `name` in (:xxx)
                $expr = $_where[1];
                $value = $_where[2];
                if (0 === strcmp($expr, 'in')) {
                    // `name` in (:xxx)
                    $format = sprintf('%s in (:%s)', $fieldAndAlias, $filedAlias);
                } else {
                    // `name` like :xxx
                    // `name` > :xxx
                    $format = sprintf('%s %s :%s', $fieldAndAlias, $expr, $filedAlias);
                }
            }
            $qb->andWhere($format);
            $qb->setParameter($filedAlias, $value);
        }
    }
}
